package com.example.sqlSession;

import com.example.pojo.Configuration;
import com.example.pojo.MappedStatement;

import java.beans.IntrospectionException;
import java.lang.reflect.*;
import java.sql.SQLException;
import java.util.List;

public class DefaultSqlSession implements SqlSession {

    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    public <E> List<E> selectList(String statementid, Object... params) throws IllegalAccessException, IntrospectionException, InstantiationException, NoSuchFieldException, SQLException, InvocationTargetException, ClassNotFoundException {
        //将要完成对simpleExecutor里的query调用
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MappedStatement mappedStatement = configuration.getMappedStatmentMap().get(statementid);
        List<Object> query = simpleExecutor.query(configuration, mappedStatement, params);

        return (List<E>)query;

    }

    public <T> T selectOne(String statementid, Object... params) throws IllegalAccessException, ClassNotFoundException, IntrospectionException, InstantiationException, SQLException, InvocationTargetException, NoSuchFieldException {
        List<Object> objects = selectList(statementid, params);
        if(objects.size()==1){
            return (T)objects.get(0);
        }else {
            throw new RuntimeException("查询结果集为空或多个");
        }


    }

    public <T> T getMapper(Class<T> mapperClass) {
        // 使用JDK动态代理来DAO接口生成接口代理对象，并返回
        Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                // 执行jdbc
                // 根据不同情况，来调用 selectOne  、selectList

                // 准备参数  statementId : mapper.xml sql 的唯一标识
                String methodName = method.getName();
                String methodClassName = method.getDeclaringClass().getName();

                String statementId = methodClassName+"."+methodName;

                //获取返回值类型
                Type genericReturnType = method.getGenericReturnType();
                // 判断是否进行类型 泛型
                if(genericReturnType  instanceof ParameterizedType){
                    return  selectList(statementId,args);
                }


                return selectOne(statementId,args);



            }
        });
        return (T) proxyInstance;
    }


}
